package display;

import java.io.File;
import java.util.Scanner;

import reader.MenuReader;

import menu.Menu;
import menu.MenuElement;


public class TextMenuDisplay implements MenuDisplay {

    private final MenuReader aReader;
    private Scanner aScanner;
    private Character aSelection;
    private Menu aLastMenu;

    public TextMenuDisplay(MenuReader pReader) {
        assert pReader != null;
        
        aReader = pReader;
        aScanner = new Scanner(System.in);
    }

    public Menu display(Menu pMenu) {
        assert pMenu != null;
        
        Menu lCurrentMenu = pMenu;

        boolean lRunDisplay;
        do {
            lRunDisplay = false;
            aSelection = displayMenu(lCurrentMenu);
            
            // Check for invalid input
            if(null == aSelection || !lCurrentMenu.contains(aSelection)) {
                System.out.println("Invalid input <"+aSelection+">. Please enter select one of the available options.");
                lRunDisplay = true;
                continue;
            }
            
            // Check if link to submenu
            MenuElement lElement = lCurrentMenu.getElement(aSelection);
            if(lElement.isLink()) {
                File lNewMenuFile = new File(lElement.getLink());
                lCurrentMenu = aReader.getMenu(lNewMenuFile);
                lRunDisplay = true;
            }
        } while(lRunDisplay);
        
        aLastMenu = lCurrentMenu;
        return aLastMenu;
    }

    public int getSelection() {
        return aLastMenu.getElement(aSelection).getID();
    }
    
    // Print the whole menu and return user input
    private Character displayMenu(Menu pMenu) {
        assert pMenu != null;
        
        System.out.println("=== " + pMenu.getTitle() + " ===");

        for(int i = 0; i < pMenu.getLength(); i++) {
            displayElement(pMenu.getElement(i));
        }

        System.out.println(pMenu.getPrompt());
        String lResult = aScanner.nextLine();
        
        if(lResult.length() > 0) {
            return lResult.charAt(0); 
        }
        return null;
    }

    private void displayElement(MenuElement pElement) {
        assert pElement != null;
        
        String lResult = "(" + pElement.getHotkey() + ")" 
        + " - " + pElement.getDescription();
        System.out.println(lResult);
    }

}
